
$(function(){
    var awardStock = {
        awardStockItems:{},
        editFlg: false,
        repeatFlg: false
    };

    awardStock.awardStockItems.no = com.focusPage("#no");
    awardStock.awardStockItems.name = com.focusPage("#name");
    awardStock.awardStockItems.num = com.focusPage("#num");
    awardStock.awardStockItems.type = com.focusPage("#type");
    awardStock.awardStockItems.price = com.focusPage("#price");
    awardStock.awardStockItems.content = com.focusPage("#content");
    awardStock.awardStockItems.Warehousing = com.focusPage("#Warehousing");
    awardStock.awardStockItems.Warehousend = com.focusPage("#Warehousend");
    awardStock.awardStockItems.no2 = com.focusPage("#no2");
    awardStock.awardStockItems.name2 = com.focusPage("#name2");
    awardStock.awardStockItems.nownum = com.focusPage("#nownum");
    awardStock.awardStockItems.achievementType = com.focusPage("#achievementType");
    awardStock.awardStockItems.identificationType =  com.focusPage("#identificationType");

    var displayFunc  = (function(){
        /*表格样式*/
        var renderList = function(tableId,listData){
            var $tableWrap = com.focusPage('#' + tableId);

            if(listData && listData.length){
                var $ulTitle = createTableTitle();
                var $ulData = $('<ul></ul>').addClass('flex-table');
                $tableWrap.append($ulTitle).append($ulData);

                $.each(listData,function(i, v){
                    var $liLine = creatLine(i, v, i == listData.length - 1);
                    $liLine.appendTo($ulTitle);
                });
            }
        };

        /*表格头*/
        var createTableTitle = function(){
            var $ulTitle = $('<ul></ul>').addClass('flex-table');
            var $liTitle = $('<li></li>').addClass('line table-title');

            var $indexWrap = $('<div></div>').addClass('line-wrap order').html($('<div></div>'));
            var $contentWrap = $('<div></div>').addClass('line-wrap  content col9');
            var titleName ='编号,名称,数量,价格,类型,备注,状态,库存标识,业绩标识';

            $.each(titleName.split(','), function (i, v) {
                var $cell = $('<div></div>').addClass('cell').html(v);
                $cell.appendTo($contentWrap);
            });

            var $optionWrap = $('<div></div>').addClass('line-wrap action').html($('<div>操作</div>').addClass('cell option'));

            $liTitle.append($indexWrap).append($contentWrap).append($optionWrap).appendTo($ulTitle);

            return $ulTitle;
        };
        /*表格体*/
        var creatLine = function (i, v, lastFlag) {
            var $liLine = $('<li></li>').addClass('line');
            var id = i + 1;
            var $indexWrap = $('<div></div>').addClass('line-wrap order').html($('<div></div>').addClass('cell index').html(id));
            var $contentWrap = $('<div></div>').addClass('line-wrap content col9');
            var type = {
                "0": "劵",
                "1": "物品",
                "2": "特殊劵",
                "3": "特殊物品"
            };
            var propertyArr = [
                [v.no,'grey'],
                [v.name,'grey'],
                [v.num,'grey'],
                [v.price,'grey'],
                [type[v.type],'grey'],
                [v.content,'grey'],
                [v.status =="0" ? "启用" : "禁用",'red'],
                [v.achievementType=="0" ? "不计算业绩" : "计算业绩",'red'],
                [v.identificationType=="0" ? "不加入库存" : "加入库存",'red']
            ];

            $.each(propertyArr, function (i, v) {
                var $cell = $('<div></div>').addClass('cell ' + v[1]).html(v[0]);
                $cell.appendTo($contentWrap);
            });

            var $optionWrap = $('<div></div>').addClass('line-wrap action');
            var $cellOption = $('<div></div>').addClass('cell option');

            var $btnGroup = $('<div></div>').addClass('btn-group');
            var $btn = $('<button></button>').addClass('btn btn-primary dropdown-toggle').attr('data-toggle', 'dropdown').append('操作').append('<i class="icon-angle-down"></i>');
            var $btnUl = $('<ul></ul>').addClass('dropdown-menu').addClass(lastFlag ? 'bottom-up' : '');
            var $btnStart = $('<li></li>').append($('<a></a>').html('启用'));
            var $btnBan = $('<li></li>').append($('<a></a>').html('禁用'));
            var $warehousing = $('<li></li>').append($('<a></a>').html('入库'));
            var $warehousend = $('<li></li>').append($('<a></a>').html('出库'));
            var $inventory = $('<li></li>').append($('<a></a>').html('盘点'));
            var $record = $('<li></li>').append($('<a></a>').html('记录'));

            $btnUl.append($btnStart).append($btnBan).append($warehousing).append($warehousend).append($inventory).append($record)

            $btnGroup.append($btn).append($btnUl).appendTo($cellOption);

            $cellOption.appendTo($optionWrap);

            $liLine.append($indexWrap).append($contentWrap).append($optionWrap);

            /*状态启用*/
            $btnStart.click(function(){
                startStatus(v.asId, v.status, function(){
                    layer.closeAll();
                    layer.msg('启用成功',{icon:1});
                });
            });

            /*状态禁用*/
            $btnBan.click(function(){
                stopStatus(v.asId, v.status, function(){
                    layer.closeAll();
                    layer.msg('禁用成功',{icon:1});
                });
            });

            $warehousend.click(function(){
                if(v.identificationType == 0){
                    com.showAlert(com.warning, "此商品禁止出库!");
                    return
                }
                com.cleanItems(awardStock.awardStockItems);
                editBrand(v);
                editReadOnly();
                com.focusPage("#join").hide();
                com.focusPage("#stock").hide();
                com.focusPage("#leave").show();
                openlayer(function(index, layero){
                    if(com.validate('form2'))
                        return;
                    updateDataEnd(v, function(){
                        layer.closeAll();
                    });
                },2);
            });
            $warehousing.click(function(){
                if(v.identificationType == 0){
                    com.showAlert(com.warning, "此商品禁止入库!");
                    return
                }
                com.cleanItems(awardStock.awardStockItems);
                editBrand(v);
                editReadOnly();
                com.focusPage("#leave").hide();
                com.focusPage("#stock").hide();
                com.focusPage("#join").show();
                openlayer(function(index, layero){
                    if(com.validate('form2'))
                        return;
                    updateDataIng(v, function(){
                        layer.closeAll();
                    });
                },2);
            });

            $inventory.click(function(){
                if(v.identificationType == 0){
                    com.showAlert(com.warning, "此商品禁止盘点!");
                    return
                }
                com.cleanItems(awardStock.awardStockItems);
                editBrand(v);
                editReadOnly();
                com.focusPage("#join").hide();
                com.focusPage("#leave").hide();
                com.focusPage("#stock").show();
                openlayer(function(index, layero){
                    if(com.validate('form2'))
                        return;
                    updateData(v, function(){
                        layer.closeAll();
                    });
                },2);
            });

            $record.click(function(){
                openLayerSwitch('stockRecordPopUp', v.asId, '记录','views/information/stockRecord.html');
            });


            return $liLine;
        };

        return {
            init : function(tableId,listData){
                com.focusPage('#' + tableId).html(null);
                renderList(tableId,listData);
            },
            drawLine : function(v){
                return creatLine(v);
            }
        };
    })();

    /*分页*/
    var _condArr = ['prizeName','prizeNo'];
    var awardStockSeacher = new Searcher();
    awardStockSeacher.init( _condArr, "condList", api.information.pageAwardStock, function(data){
        displayFunc.init('resultList', data);
    }, "pagenation", "pageAwardPostData", null, false, null, function() {
        var $adda = $('<a></a>').addClass('btn btn-minier btn-primary pull-left').attr('name', 'addQuotationVersion').css('margin', '0px 3px');
        var $addi = $('<i></i>').addClass('icon-plus bigger-110').appendTo($adda);
        var $addspan = $('<span></span>').text('添加').appendTo($adda);

        $adda.click(function(){
            com.cleanItems(awardStock.awardStockItems);
            openlayer(function(index, layero) {
                if (com.validate('form1'))
                    return;
                saveData(function () {
                    layer.closeAll();
                });
            },1);
        });
        return [$adda];
    },'resultList');

    function openLayerSwitch(id, asid, title, url) {
        console.log(asid);
        console.log("进入弹窗");
        var $PopUp = com.focusPage('#' + id);
        console.log($PopUp)
        $PopUp.attr({'data-asid': asid});
        //弹出即全屏
        var index = layer.open({
            type: 1,
            skin: 'layui-layer-lan',
            title: title,
            content: $PopUp,
            area: ["1200px", ( $(window).height() * 0.84 < 800 ? $(window).height() * 0.84 : 800 ) + "px"],
            maxmin: false,
            zIndex: 9000,
            success: function (layer, index) {
                console.log("成功")
                $PopUp.load(url);
                awardStockSeacher.doSearch();
            },
            end: function () {
                console.log("失败s")
                $PopUp.attr({'data-asid': null});
                $PopUp.empty();
                awardStockSeacher.doSearch();
            }
        });
    }

    function openlayer(callback,variable){
        layer.closeAll();
        layer.open({
            type: 1,
            title:" ",
            content: com.focusPage('#layerAdd'+ variable),
            area: ( $(window).width()*0.6 < 620 ?  $(window).height()*0.6 : 620 )+"px",
            maxmin: false,
            zIndex:9000,
            btn: ['确定', '取消'],
            yes: function(index, layero){
                callback(index,layero);
            },
            btn2: function(index, layero){
                //按钮【按钮二】的回调
                com.clearValidator();
            },
            cancel: function(){
                //右上角关闭回调
            }
        });
    }

    /*状态信息验证*/
    function startStatus(id, status, callback){
        if(status == "1"){
            com.post(api.information.updateAwardStockForStatus,{
                "awardStock.asId" : id,
                "awardStock.status" : 0
            },function(res){
                callback();
                awardStockSeacher.doSearch();
            });
        }else{
            layer.alert('已经启用', {
                icon: 0,
                skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
            });
        }
    }

    function stopStatus(id, status, callback){
        if(status == "0"){
            com.post(api.information.updateAwardStockForStatus,{
                "awardStock.asId" : id,
                "awardStock.status" : 1
            },function(res){
                callback();
                awardStockSeacher.doSearch();
            });
        }else{
            layer.alert('已经禁用', {
                icon: 0,
                skin: 'layer-ext-moon'
            });
        }
    }

    /*添加信息*/
    function saveData(callback){
        var no = awardStock.awardStockItems.no.val();
        var name = awardStock.awardStockItems.name.val();
        var type = awardStock.awardStockItems.type.val();
        var num = awardStock.awardStockItems.num.val();
        var price = awardStock.awardStockItems.price.val();
        var content = awardStock.awardStockItems.content.val();
        var achievementType = awardStock.awardStockItems.achievementType.val();
        var identificationType = awardStock.awardStockItems.identificationType.val()

            com.post(api.information.addAwardStock, {
                "type": 0,
                "awardStock.no": no,
                "awardStock.name":name,
                "awardStock.type":type,
                "awardStock.num": num,
                "awardStock.price":price,
                "awardStock.content":content,
                "awardStock.achievementType": achievementType,
                "awardStock.identificationType": identificationType
            }, function(res){
                    callback();
                    awardStockSeacher.doSearch();
            });
    }

    function updateDataEnd(v, callback){
        var warehousend = com.focusPage("#Warehousend").val();
        com.post(api.information.updateAwardStockOutStock, {
            "awardStock.asId": v.asId,
            "awardStock.num": parseInt(warehousend),
            "type": 1,
            "awardStock.price":v.price,
            "awardStock.content":v.content

        }, function(res){
            callback();
            awardStockSeacher.doSearch();
        });
    }
    function updateDataIng(v, callback){
        var warehousing = com.focusPage("#Warehousing").val();
        com.post(api.information.updateAwardStockEnterStock, {
            "type": 0,
            "awardStock.asId": v.asId,
            "awardStock.num": parseInt(warehousing),
            "awardStock.price":v.price,
            "awardStock.content":v.content
        }, function(res){
            callback();
            awardStockSeacher.doSearch();
        });
    }

    function updateData(v, callback){
        var nownum = com.focusPage("#nownum").val();
        if(nownum != "" && nownum > v.num){
            type = 2
        }
        else if(nownum != "" && nownum < v.num){
            type = 3
        }
        com.post(api.information.updateAwardStockInventoryStock, {
            "type": type,
            "awardStock.asId": v.asId,
            "awardStock.num": nownum,
            "awardStock.price":v.price,
            "awardStock.content":v.content
        }, function(res){
            callback();
            awardStockSeacher.doSearch();
        });
    }

    // function deleteAwardStock(v){
    //     com.post(api.information.deleteAwardStockByAsId, {
    //         "awardStock.asId": v
    //     }, function(res){
    //         awardStockSeacher.doSearch();
    //     });
    // }

    function editBrand(v){
        awardStock.awardStockItems.no2.val(v.no);
        awardStock.awardStockItems.name2.val(v.name);
        awardStock.awardStockItems.nownum.val(v.num)
    }

    function editReadOnly() {
        var $layerAdd = com.focusPage('#layerAdd2');
        $layerAdd.find("#no2").attr('disabled', 'disabled');
        $layerAdd.find("#name2").attr('disabled', 'disabled');
    }
});
